import json

import akshare as ak
import pandas as pd
import requests as requests

from python_quant.common.excel import write_excel_xls, write_excel_xls_append


def get_report_date():
    url = 'https://datacenter-web.eastmoney.com/api/data/v1/get?reportName=RPT_FREEHOLDERS_HD_REPORTDATE&columns' \
          '=END_DATE%2CREPORT_DATE_NAME&sortColumns=END_DATE&sortTypes=-1&source=WEB&client=WEB&pageSize=500&filter=(' \
          'END_DATE%3E%3D%272015-03-31%27)&_=1663416388832 '
    content = requests.get(url)
    json_content = json.loads(content.text)
    json_content_result = json_content['result']['data']
    report_date_list = list()
    for date_info in json_content_result:
        date_str = date_info['END_DATE']
        date = date_str.replace(" 00:00:00", "")
        date = date.replace("-", "")
        if int(date) > 20191231:
            report_date_list.append(date)
    return report_date_list


if __name__ == '__main__':
    date_list = get_report_date()

    ignal_list = list()
    signal_list = list()

    for date in date_list:
        date_ignal_list = list()
        date_signal_list = list()
        stock_gdfx_free_holding_analyse_em_df = ak.stock_gdfx_free_holding_analyse_em(date=date)
        for index, row in stock_gdfx_free_holding_analyse_em_df.iterrows():
            if float(row['公告日后涨跌幅-10个交易日']) >= 10 and row['期末持股-持股变动'] == '新进':
                date_signal_list.append(row['股东名称'])
            else:
                if row['期末持股-持股变动'] == '新进':
                    date_ignal_list.append(row['股东名称'])
        signal_list.extend(date_signal_list)
        ignal_list.extend(date_ignal_list)

    signal_list_result = pd.value_counts(signal_list)
    print(signal_list_result)
    ignal_list_result = pd.value_counts(ignal_list)
    print(ignal_list_result)

    signal_success_rate = list()
    for signal in signal_list_result.items():
        signal_sucess = (signal[0], 100, signal[1], 0)
        for ignal in ignal_list_result.items():
            if signal[0] == ignal[0]:
                sucess_rate = signal[1] / (signal[1] + ignal[1]) * 100
                signal_sucess = (signal[0], sucess_rate, signal[1], ignal[1])
        signal_success_rate.append(signal_sucess)

    signal_success_rate = sorted(signal_success_rate, key=lambda x: x[1], reverse=True)
    # print(signal_success_rate)

    book_name_xls = 'xy.xls'
    sheet_name_xls = 'x'
    value_title = [["股东名称", "成功率", "成功次数", "失败次数"]]
    write_excel_xls(book_name_xls, sheet_name_xls, value_title)

    for signal_scuess in signal_success_rate:
        print(signal_scuess)
        value1 = [[signal_scuess[0], signal_scuess[1], signal_scuess[2], signal_scuess[3]]]
        write_excel_xls_append(book_name_xls, value1)
